<?php
namespace app\common\model;
use think\Model;
use think\Cache;
class Label extends Model{
	
	
	/**
	 * 行业
	 * @param number $industry_id
	 * @return mixed
	 */
	public  function industry($industry_id=0){
		
		$cache=new Cache();
		$result=$cache->get('industry_'.$industry_id);
		if($result){
			$result=unserialize($result);
		}else{
			$data=db('industry')->field('id,industry_name,pid')->select();
			$result=$this->arr2tree($data,$industry_id);
			$cache->set('industry_'.$industry_id,serialize($result),3600);
		}
		
		
		return $result;
	}
	/**
	 * 城市
	 * @param number $city_id
	 * @return mixed
	 */
	public  function city($city_id=0){
		
		$cache=new Cache();
		$result=$cache->get('city_'.$city_id);
		if($result){
			$result=unserialize($result);
		}else{
			$data=db('city')->field('id,city_name,pid')->select();
			$result=$this->arr2tree($data,$city_id);
			$cache->set('city_'.$city_id,serialize($result),3600);
		}
		
		
		return $result;
	}
	/**
	 * 产业链
	 * @param number $chain_id
	 * @return mixed
	 */
	public  function chain($chain_id=0){
		
		$cache=new Cache();
		$result=$cache->get('chain_'.$chain_id);
		if($result){
			$result=unserialize($result);
		}else{
			$data=db('chain')->field('id,chain_name,pid')->select();
			$result=$this->arr2tree($data,$chain_id);
			$cache->set('chain_'.$chain_id,serialize($result),3600);
		}
		
		
		return $result;
	}
	// 将数据按照所属关系封装 见图2
	private function arr2tree($tree, $rootId = 0) {
		$return = array();
		foreach($tree as $leaf) {
			if($leaf['pid'] == $rootId) {
				foreach($tree as $subleaf) {
					if($subleaf['pid'] == $leaf['id']) {
						$leaf['children'] = $this->arr2tree($tree, $leaf['id']);
						break;
					}
				}
				$return[] = $leaf;
			}
		}
		return $return;
	}
	
	
}